package com.example.spring_java_oj.service.userInfo;

import com.example.spring_java_oj.Util.FileUtil;
import com.example.spring_java_oj.mapper.ProblemMapper;
import com.example.spring_java_oj.mapper.UserInfoMapper;
import com.example.spring_java_oj.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.UUID;

@Service
@Slf4j
public class UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private ProblemMapper problemMapper;

    public UserInfo queryByName(String userName) {
        return userInfoMapper.queryByName(userName);
    }

    public UserInfo queryById(Integer userId) {
        return userInfoMapper.queryById(userId);
    }


    public CompileResponse run(Integer id, String code, HttpServletRequest request) {
        CompileResponse response = new CompileResponse();
        Problem problem = problemMapper.getProblem(id);
        if (problem == null){
            log.info("该题目不存在");
            return null;
        }
        String testCode = problem.getTestCode();
        String finalCode = response.mergeCode(code, testCode);
        HttpSession session = request.getSession();
        String finalCodeFile = "./tmp/" + session.getAttribute("username")  + id + "/" + "finalCodeFile.txt";
        FileUtil.writeFile(finalCodeFile, code);
        if(finalCode == null){
            response.setReason("代码不符合要求!");
            response.setError(3);
            return response;
        }
        Task task = new Task(id, request);
        Answer answer = task.compileAndRun(finalCode);

        response.error = answer.getError();
        response.reason = answer.getReason();
        response.stdout = answer.getStdout();
        return response;
    }

    public boolean regster(String username, String passwordA, String passwordB) {
        if(!passwordA.equals(passwordB)){
            return false;
        }
        int n = userInfoMapper.register(username, passwordA);
        if(n == 1){
            return true;
        }
        return false;
    }

}
